<template>
  <view class="product w100 h100 flex-col" :style="{ '--theme': themeColor }">
    <nav-bar :title="type == 'add' ? '添加商品' : '编辑商品'" />
    <view class="page flex1 flex-col">
      <view class="content flex-col flex1">
        <u--form :model="form" :rules="rules" ref="form1">
          <view class="classify">
            <view class="top flex flexAIC">
              <view class="left">商品分类</view>
              <view
                :class="[
                  'right flex1 flexAIC',
                  pubUserInfo.mainShopStatus ? '' : 'disabledBg',
                ]"
              >
                <u-form-item
                  prop="categoryId"
                  labelWidth="0rpx"
                  @click="ChooseClassOption()"
                  class="flex1"
                >
                  <u--input
                    v-model="classOptions[form.categoryId]"
                    disabled
                    :disabledColor="pubUserInfo.mainShopStatus ? '#ffffff' : ''"
                    placeholder="请选择商品分类"
                    border="none"
                  />
                  <u-icon slot="right" name="arrow-down" />
                </u-form-item>
              </view>
            </view>
            <view class="msg">
              <view class="title">商品信息</view>
              <view class="name marginBottom-30">
                <view class="title marginBottom-30">商品名称</view>
                <view>
                  <u-form-item prop="title" labelWidth="0rpx">
                    <view
                      :class="[
                        'show-count',
                        pubUserInfo.mainShopStatus ? '' : 'disabledBg',
                      ]"
                    >
                      <u--input
                        v-model="form.title"
                        maxlength="60"
                        :showWordLimit="true"
                        placeholder="请输入商品名称"
                        border="none"
                        :disabled="!pubUserInfo.mainShopStatus"
                      />
                      <view class="num">{{ form.title.length }} / 60</view>
                    </view>
                  </u-form-item>
                </view>
              </view>
              <view class="imgs">
                <view class="title marginBottom-23">商品主图</view>
                <view class="tip"
                  >只能上传jpg/png文件,且每张不超过1mb，最多可上传10张</view
                >
                <view class="list">
                  <u-form-item prop="displayInfo.imageList" labelWidth="0rpx">
                    <view class="image-container">
                      <template v-for="(item, index) in images">
                        <view
                          :key="index"
                          class="image-item"
                          @click="$myTool.previewImage(item.src)"
                        >
                          <image :src="item.src" mode="aspectFill" />
                          <view
                            v-if="item.uploading"
                            class="uploading-tips center loading"
                          >
                            <u-loading-icon
                              text="上传中"
                              color="#fff"
                              textColor="#fff"
                              textSize="14"
                              :vertical="true"
                            ></u-loading-icon>
                          </view>
                          <view
                            v-if="item.error"
                            class="uploading-tips center error"
                            >上传失败</view
                          >
                          <view
                            class="delete center"
                            @click.stop="deletePic(index)"
                          >
                            <u-icon
                              name="close"
                              size="14"
                              color="#fff"
                            ></u-icon>
                          </view>
                        </view>
                      </template>
                      <view
                        class="image-item add center"
                        v-if="
                          pubUserInfo.mainShopStatus && !(images.length >= 10)
                        "
                        @click="chooseImage"
                      >
                        <u-icon name="plus" size="28"></u-icon>
                      </view>
                    </view>
                  </u-form-item>
                </view>
              </view>
              <view class="spec">
                <view class="flex-btw flexAIC" v-if="form.specList.length == 0">
                  <view class="title">商品价格</view>
                  <view class="spec-right flex1 flexAIC">
                    <u-form-item
                      prop="productPrice"
                      labelWidth="0rpx"
                      class="flex1"
                    >
                      <u--input
                        v-model="form.productPrice"
                        disabledColor="#ffffff"
                        placeholder="请输入商品价格"
                        border="none"
                        type="digit"
                        maxlength="9"
                        :formatter="formatter"
                      />
                      <view slot="right">元</view>
                    </u-form-item>
                  </view>
                </view>
                <view class="flex-btw flexAIC" v-if="form.specList.length == 0">
                  <view class="title">库存</view>
                  <view class="spec-right flex1 flexAIC">
                    <u-form-item
                      prop="productInventory"
                      labelWidth="0rpx"
                      class="flex1"
                    >
                      <u--input
                        v-model="form.productInventory"
                        placeholder="请输入商品库存"
                        border="none"
                        type="number"
                        maxlength="5"
                        clearable
                      />
                      <!-- <u-icon
                        slot="right"
                        name="close-circle"
                        @click="form.productInventory = ''"
                      /> -->
                    </u-form-item>
                  </view>
                </view>
                <view class="flex-btw flexAIC">
                  <view class="title flexAIC">规格</view>
                  <view class="spec-right flex1 flexAIC">
                    <u-form-item
                      prop="specList"
                      labelWidth="0rpx"
                      @click="toSetSpec()"
                      class="flex1"
                    >
                      <u--input
                        v-model="specLength"
                        disabled
                        disabledColor="#ffffff"
                        placeholder="(选填)如杯型、分量等"
                        border="none"
                      />
                      <u-icon slot="right" name="arrow-right" />
                    </u-form-item>
                  </view>
                </view>
                <view class="flex-btw flexAIC">
                  <view class="title flexAIC">规格明细</view>
                  <view class="spec-right flex1 flexAIC" @click="toSetSpec(1)">
                    <u-form-item
                      prop="skuList"
                      labelWidth="0rpx"
                      @click="toSetSpec(1)"
                      class="flex1"
                    >
                      <u--input
                        v-model="skuLength"
                        disabled
                        disabledColor="#ffffff"
                        placeholder="(选填)价格和库存"
                        border="none"
                      />
                      <u-icon slot="right" name="arrow-right" />
                    </u-form-item>
                  </view>
                </view>
              </view>
              <view class="remark">
                <view class="title marginBottom-30">商品描述</view>
                <view>
                  <u--textarea
                    v-model="form.description"
                    placeholder="请输入内容"
                    count
                    maxlength="200"
                    :disabled="!pubUserInfo.mainShopStatus"
                  />
                </view>
              </view>
              <view class="hint marginTop-25">
                提示：保存后分店不显示商品，商品上架后才显示在分店；
              </view>
            </view>
          </view>
        </u--form>
        <view class="bottom">
          <view class="btns flex flex-btw">
            <view
              :class="['center', !pubUserInfo.mainShopStatus ? 'save' : '']"
              @click="save()"
            >
              <u-button :disabled="saveLoading">保存</u-button>
            </view>
            <view
              class="center"
              @click="save('up')"
              v-if="pubUserInfo.mainShopStatus"
            >
              <u-button :disabled="saveLoading">保存并上架</u-button>
            </view>
          </view>
        </view>
      </view>
    </view>
    <classify-pop
      :visible.sync="showChooseClass"
      :categoryId="form.categoryId"
      @chooseClass="chooseClass"
    />
  </view>
</template>

<script>
import classifyPop from "@/components/pageComponents/sp-product/classify-pop";
import {
  getProductDetail,
  addProduct,
  updateProduct,
  getStoreList,
} from "@/service/api/sp-product/index";
import { mapState, mapActions } from "vuex";

export default {
  data() {
    return {
      rules: {
        categoryId: [
          {
            type: "number",
            required: true,
            message: "请选择商品分类",
            trigger: ["blur", "change"],
          },
        ],
        title: [
          {
            type: "string",
            required: true,
            message: "请输入商品名称",
            trigger: ["blur", "change"],
          },
        ],
        specList: [
          {
            type: "array",
            // min: 1,
            // required: true,
            message: "请设置规格",
            trigger: ["blur", "change"],
          },
        ],
        skuList: [
          {
            type: "array",
            // min: 1,
            // required: true,
            message: "请设置规格明细",
            trigger: ["blur", "change"],
          },
        ],
        "displayInfo.imageList": [
          {
            type: "array",
            min: 1,
            required: true,
            message: "请上传图片",
          },
        ],
        productPrice: [
          {
            type: "number",
            required: true,
            message: "请输入商品价格",
            trigger: ["blur", "change"],
          },
          {
            pattern: /^([1-9]\d{0,5}|0)(\.\d{1,2})?$|^1000000(\.0{1,2})?$/,
            transform(value) {
              return String(value);
            },
            message: "请输入区间0.01-999999.99",
          },
        ],
        productInventory: [
          {
            type: "number",
            required: true,
            message: "请输入商品库存",
            trigger: ["blur", "change"],
          },
        ],
      },
      showChooseClass: false,
      value2: "",
      value: "",
      type: "add",
      form: {
        goodsType: 100, // 商品类型100: 实物商品(物流), 200: 券包(虚拟商品), 300: 同城配送/自提
        // 关联物品
        goodsItems: [],
        couponVerRadio: "COUPON2",
        categoryId: "", // 商品类目
        categoryIds: [], // 商品类目
        brandId: 0, // 商品品牌
        goodsNo: "", // 商品编码
        barCode: "", // 商品条码
        goodsUnit: "件", // 商品单位
        title: "", // 商品标题
        subTitle: "", // 商品子标题
        description: "", // 商品描述
        specList: [], // 规格信息
        // 规格信息
        skuList: [],
        // 参数 服务信息
        goodsExt: {
          paramList: [],
          supportList: [],
        },
        // 限制规则
        goodsRule: {
          canUseDiscount: false,
          limited: false,
          memberType: 0, // 0:所有顾客, 1:会员, 2:仅指定会员
          cardIdList: [],
          limitNum: "",
          payChannels: ["1"],
        },
        // 预售
        presell: false,
        goodsPresell: {
          type: "FULL",
          depositType: 0,
          depositQuota: null,
          limitTime: true,
          preDate: null,
          beginTime: null,
          endTime: null,
          afterTheEnd: 0,
          remainingBeginTime: null,
          remainingEndTime: null,
          defaultRule: 0,
          defaultFineType: 0,
          defaultFine: null,
          prepareType: 1,
          prepareTime: null,
          prepareUnit: "DAYS",
          prepareBeginTime: null,
          cancelRule: 0,
          cancelFreeTime: null,
          cancelChargeType: 0,
          cancelCharge: null,
          remark: null,
        },
        // 预览信息
        displayInfo: {
          detailImages: [],
          imageList: [],
        },
        goodsDelivery: {
          canExpress: true,
          expressPrepare: null,
          expressPrepareUnit: "HOURS",
          canLocalDelivery: true,
          localPrepare: null,
          localPrepareUnit: "HOURS",
          canSelfPickup: true,
          selfPickupPrepare: null,
          selfPickupPrepareUnit: "HOURS",
        },
        goodsBargains: [], // 加购
        specInputValueExcl: null, // specInput临时绑定值
        productPrice: "",
        productInventory: 9999,
      },
      classOptions: "",
      goodsId: "",
      saveLoading: false,
      images: [],
      StoreList: [],
    };
  },
  components: {
    classifyPop,
  },
  computed: {
    themeColor({ $theme }) {
      return $theme.themeColor.primary;
    },
    specLength() {
      return this.form.specList.length > 0
        ? `共${this.form.specList.length}项`
        : "";
    },
    skuLength() {
      return this.form.skuList.length > 0 && this.form.specList.length > 0
        ? `共${this.form.skuList.length}项`
        : "";
    },
    ...mapState("sp-common/auth", ["pubUserInfo", "token"]),
    ...mapState("sp-product/index", ["classifyList"]),
    ...mapState("sp-product/index", {
      vxSkus: "skuList",
      vxspecList: "specList",
      vxstoreList: "storeList",
    }),
  },
  async mounted() {
    if (this?.$Route?.query?.goodsId) {
      let { type } = this?.$Route?.query;
      this.type = type;
      this.goodsId = this?.$Route?.query?.goodsId;
      await this.getProductDetail();
    }
    await this.searchClass();
    await this.initSkus();
    await this.getStoreList();
  },
  watch: {
    classifyList(val) {
      this.searchClass();
    },
  },
  onReady() {
    this.$refs.form1.setRules(this.rules);
  },
  methods: {
    ...mapActions("sp-product/index", [
      "setSkuList",
      "setSpecList",
      "setStoreList",
    ]),
    chooseClass(data) {
      let { categoryId } = data;
      this.form.categoryId = String(categoryId);
      this.$refs.form1.validateField("categoryId");
    },
    getProductDetail() {
      return new Promise((resolve, reject) => {
        let {
          pubUserInfo: { mainShopStatus, shopId: pubShopId },
          goodsId,
          type,
        } = this;
        getProductDetail({
          mainShopStatus,
          goodsId,
          copy: type == "copy",
        }).then((res) => {
          this.form = res;
          let { specList, skuList, pubStoreSkuLiVOList } = res;
          if (specList.length == 0 && skuList.length == 1) {
            if (type == "edit") {
              let { inventory, price } = pubStoreSkuLiVOList.find(
                (ele) => ele.shopId == pubShopId
              ).skus[0];
              this.form.productInventory = inventory;
              this.form.productPrice = price / 100;
            }
            if (type == "copy") {
              this.form.productInventory = 9999;
              // this.form.productPrice = "";
            }
          }
          if (res?.displayInfo?.imageList.length > 0) {
            res?.displayInfo?.imageList.forEach((item) => {
              item = process.env.VUE_APP_BASE_FileUrl + item;
              this.images.push({
                src: item,
              });
            });
          }

          resolve();
        });
      });
    },
    searchClass() {
      let classPar = { "": "" };
      this.classifyList.forEach((item) => {
        classPar[item.id] = item.title;
      });
      this.classOptions = classPar;
    },
    toSetSpec(active) {
      this.$myTool.jumpPage("specSet", {
        type: this.type,
        activeTab: active ? 1 : 0,
      });
    },
    initSkus() {
      let {
        form: { skuList, specList, pubStoreSkuLiVOList = [] },
        type,
      } = this;
      if (skuList.length > 0) {
        skuList.forEach((item) => {
          item.price /= 100;
          if (this.type == "copy") {
            item.price = "";
            item.inventory = 9999;
            item.status = 1;
          }
        });
      }
      if (pubStoreSkuLiVOList?.length > 0) {
        pubStoreSkuLiVOList.forEach((ele) => {
          if (ele.skus?.length > 0) {
            ele.skus.forEach((element) => {
              element.price = element.price / 100;
            });
          }
        });
      }
      this.setSkuList(skuList);
      this.setSpecList(specList);
      this.setStoreList(pubStoreSkuLiVOList);
    },
    getStoreList() {
      getStoreList({ disabled: false }).then((res) => {
        this.shopStores = res;
      });
    },
    async save(option) {
      let {
        form,
        pubUserInfo: { mainShopStatus, shopId: pubShopId },
        type,
        goodsId,
        saveLoading,
        shopStores,
        form: { specList, productInventory, productPrice, skuList,pubStoreSkuLiVOList },
      } = this;
      let pages = getCurrentPages();
      let prevPage = pages[pages.length - 2]; //上一页页面实例
      let isMultiple = specList.length > 0 && skuList.length >= 1;
      //   // 单规格商品
      const skuObj = {
        imgUrl: "",
        originPrice: "",
        price: +productPrice * 100,
        skuNo: "",
        sn: "",
        inventory: +productInventory,
        specAttrNameList: [],
        specAttrIdsList: [],
        status: option === "up" ? 1 : 0,
        specAttr1: 0,
        specAttr2: 0,
        specAttr3: 0,
        specAttr4: 0,
        specAttr5: 0,
        specAttr6: 0,
      };
      // 只有复制和编辑才会校验并且不是无规格商品
      if ((type == "copy" || type == "edit") && isMultiple) {
        if (!this.verifySpec()) {
          return;
        }
      }
      this.$refs.form1.validate().then((res) => {
        if (res) {
          this.saveLoading = true;
          if (saveLoading) return;
          uni.showLoading({
            title: "保存中...",
            icon: "",
          });
          form.mainShopStatus = mainShopStatus;
          console.log(isMultiple);
          if (isMultiple) {
            // 规格所有价格*100
            if (form?.skuList?.length > 0) {
              form?.skuList.map((ele) => {
                ele.price *= 100;
                ele.status = option === "up" ? 1 : 0;
              });
            }
            // 每个门店下面的数据都价格*100
            if (type == "edit") {
              form?.pubStoreSkuLiVOList.map((ele) => {
                if (ele?.skus?.length > 0) {
                  ele.skus.map((sku) => {
                    sku.price *= 100;
                  });
                }
              });
            } else {
              form?.pubStoreSkuLiVOList.map((ele) => {
                ele.skus = form?.skuList;
              });
            }
          } else {
            /* 
             新增无规格商品直接就是所有门店都是统一价格和库存
             编辑无规格商品只修改当前登录门店的数据
            */
            if (type == "add" || type == "copy" || pubStoreSkuLiVOList.length<=0) {
              shopStores.forEach((ele) => {
                ele.skus = [skuObj];
              });
              form.pubStoreSkuLiVOList = shopStores;
            } else {
              let currentShopIndex = form?.pubStoreSkuLiVOList.findIndex(
                (ele) => {
                  return ele.shopId == pubShopId;
                }
              );
              form?.pubStoreSkuLiVOList.map((ele) => {
                if (ele?.skus?.length > 0) {
                  ele.skus.map((sku) => {
                    sku.price *= 100;
                  });
                }
              });
              form.pubStoreSkuLiVOList[currentShopIndex].skus[0].price = skuObj.price;
              form.pubStoreSkuLiVOList[currentShopIndex].skus[0].inventory = skuObj.inventory;
            }
            form.skuList = [skuObj];
          }
          delete form.productPrice;
          delete form.productInventory;
          if (type === "edit") {
            form.goodsId = goodsId;
            updateProduct(form)
              .then((res) => {
                uni.showToast({
                  title: "保存商品成功",
                  icon: "none",
                  success: () => {
                    setTimeout(() => {
                      prevPage.$vm.getProduct(1);
                      uni.navigateBack({
                        delta: 1,
                      });
                      this.saveLoading = false;
                    }, 500);
                  },
                });
              })
              .catch((error) => {
                uni.showToast({
                  icon: "none",
                  title: error.msg,
                });
                this.saveLoading = false;
              });
          } else {
            addProduct(form)
              .then((res) => {
                uni.showToast({
                  title: "新增商品成功",
                  icon: "none",
                  success: () => {
                    setTimeout(() => {
                      prevPage.$vm.getProduct(1);
                      uni.navigateBack({
                        delta: 1,
                      });
                      this.saveLoading = false;
                    }, 500);
                  },
                });
              })
              .catch((error) => {
                uni.showToast({
                  icon: "none",
                  title: error.msg,
                });
                this.saveLoading = false;
              });
          }
        }
      });
    },
    verifySpec() {
      let {
        form: { pubStoreSkuLiVOList },
        falg = true,
        pubUserInfo: { shopId: pubShopId },
      } = this;
      if (pubStoreSkuLiVOList.length < 1) {
        falg = false;
      }
      if (pubStoreSkuLiVOList.length >= 1) {
        let index = pubStoreSkuLiVOList.findIndex((ele) => {
          return ele.shopId == pubShopId;
        });
        let mainShop = pubStoreSkuLiVOList[index].skus;
        mainShop.forEach((ele) => {
          if (!ele.inventory || ele.price <= 0 || !ele.price) falg = false;
        });
      }
      if (!falg) {
        uni.showModal({
          content: "存在价格/库存未配置，请先完成配置",
          showCancel: false,
          confirmText: "我知道了",
          confirmColor: this.themeColor,
        });
      }
      return falg;
    },
    saveSpec() {
      this.form.skuList = this.vxSkus;
      this.form.specList = this.vxspecList;
      this.form.pubStoreSkuLiVOList = this.vxstoreList;
      if (this.form.skuList.length <= 0 && this.form.specList.length <= 0) {
        this.form.productInventory = 9999;
        // this.form.productPrice = '';
      }
    },
    setImgList() {
      let { images } = this;
      let imgList = [];
      if (images.length > 0) {
        imgList = images.map((item) => {
          return item.src.replace(process.env.VUE_APP_BASE_FileUrl, "");
        });
      }
      this.form.displayInfo.imageList = imgList;
      this.$refs.form1.validateField("displayInfo.imageList");
    },
    ChooseClassOption() {
      if (!this.pubUserInfo.mainShopStatus) return;
      this.showChooseClass = true;
    },

    chooseImage() {
      uni.chooseImage({
        count: 10, // 最多可选择的图片数量，默认1张
        success: (res) => {
          const tempFiles = res.tempFiles;
          this.uploadImage(tempFiles);
        },
      });
    },
    uploadImage(filePathList) {
      for (let i = 0; i < filePathList.length; i++) {
        const filePath = filePathList[i].path;
        let fileType = filePath.split(".")[1].toLowerCase();
        if (
          ["png", "jpg", "jpeg"].indexOf(fileType) < 0 ||
          filePathList[i].size > 1024 * 1024
        ) {
          uni.showToast({
            title: "上传失败，仅支持1mb内、jpg/jpeg/png格式的图片",
            icon: "none",
            duration: 3000,
          });
          continue;
        }
        if (this.images.length >= 10) return;
        this.images.push({
          src: filePath,
          uploading: true,
          error: false,
        });

        // 调用uni.uploadFile方法上传图片
        uni.uploadFile({
          url: `${process.env.VUE_APP_BASE_URL}/business_admin/upload`, // 上传图片的接口地址
          filePath: filePath,
          name: "file",
          header: {
            "X-BUSINESS-TOKEN": this.token,
          },
          success: (uploadRes) => {
            let result = JSON.parse(uploadRes.data).data;
            const index = this.images.findIndex(
              (item) => item.src === filePath
            );
            this.$set(this.images, index, {
              src: `${result.baseUrl}${result.path}`,
              uploading: false,
            });
            this.setImgList();
          },
          fail: (error) => {
            const index = this.images.findIndex(
              (item) => item.src === filePath
            );
            this.$set(this.images, index, {
              src: `${result.baseUrl}${result.path}`,
              uploading: false,
              error: true,
            });
          },
        });
      }
    },
    deletePic(index) {
      this.images.splice(index, 1);
      this.setImgList();
    },
    formatter(value) {
      if (value.indexOf(".") > 0) {
        var re = /([0-9]+\.[0-9]{2})[0-9]*/;
        return value.replace(re, "$1");
      } else {
        return value;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../css/add-product.scss";
</style>
